﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ObjectTransposeApi.Structure;
using ObjectTransposeApi.Helper;

namespace ObjectTransposeApi.Handler.Property
{
    /// <summary/>
    internal class MatchPropertyHandler : AbstractPropertyHandler
    {
        /// <summary/>
        internal override IEnumerable<QueueStructure> Process(PropertyStructure propertyStructure)
        {
            // read the source property value
            object sourceValue = propertyStructure.SourcePropertyInfo.GetValue(propertyStructure.Source, null);

            // if the value is not set then exit ... this is the last item in the chain
            if (sourceValue == null)
            {
                return base._successor.Process(propertyStructure);
            }

            // is there a type mapper for the soruce value type?
            TypeMapper typeMapper = Array.Find(
                propertyStructure.TypeMappers,
                value => value.SourceType == sourceValue.GetType());

            // was a mapper found
            if (typeMapper != null)
            {
                // set the destination value
                propertyStructure.DestinationPropertyInfo.SetValue(propertyStructure.Destination, typeMapper.Converter(sourceValue), null);
            }
            else if (propertyStructure.DestinationPropertyInfo.PropertyType == propertyStructure.SourcePropertyInfo.PropertyType)
            {
                // set the destination value
                propertyStructure.DestinationPropertyInfo.SetValue(propertyStructure.Destination, sourceValue, null);
            }
            else
            {
                return base._successor.Process(propertyStructure);
            }

            // nothing to return
            return null;
        }
    }
}
